/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tpdisenio2009.mvp.display;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import tpdisenio2009.model.beans.TournamentDate;

/**
 *
 * @author Administrador
 */
public class ManageBanPeriodsTableModel extends AbstractTableModel {

    private final List<TournamentDate> dates;
    private static final int COLUMN_COUNT = 6;
    final String[] columnNames = {"Nro. de Fecha", "Fecha Inicial", "Hora Inicial", "Fecha Final", "Hora Final", "Estado"};

    public ManageBanPeriodsTableModel( List<TournamentDate> tournamentDates ) {
        dates = tournamentDates;
    }

    @Override
    public String getColumnName(int column) {
        if (( column < 0 ) || ( column > 5 ))
            return "";
        else
            return columnNames[column];
    }   

    public int getRowCount() {
        return dates.size();
    }

    public int getColumnCount() {
        return COLUMN_COUNT;
    }

    public TournamentDate getTournamentDate( int row ) {
        if (row < 0 || row >= dates.size())
            return null;
        return dates.get(row);
    }

    public TournamentDate getCurrentEditDate() {

        for ( TournamentDate date : dates ) {
            if ( date.getState().equals( TournamentDate.OPEN_DATE ) ) {
                return date;
            }
        }
        return null;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        SimpleDateFormat formateadorFecha = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat formateadorHora = new SimpleDateFormat("HH:mm:ss");
        try {
            TournamentDate date = dates.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return String.valueOf( date.getId() ) + "º";
                case 1:
                    if( date.getInitialDate() != null ) {
                        return formateadorFecha.format( date.getInitialDate() );
                    } else {
                        break;
                    }
                case 2:
                    if( date.getInitialDate() != null ) {
                        return formateadorHora.format( date.getInitialDate() );
                    } else {
                        break;
                    }
                case 3:
                    if( date.getBanDate() != null ) {
                        return formateadorFecha.format( date.getBanDate() );
                    } else {
                        break;
                    }
                case 4:
                    if( date.getBanDate() != null ) {
                        return formateadorHora.format( date.getBanDate() );
                    } else {
                        break;
                    }
                case 5:
                    return date.getState();
            }
        } catch (Exception e) {
        }
        return null;
    }

    public void cleanCell( int row, int col ) {
        setValueAt("", row, col );
    }

    @Override
    public void setValueAt( Object cellValue, int rowIndex, int columnIndex) {
        SimpleDateFormat formatTournamentDate = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S");

        String newDate = (String) cellValue;

        Date initialDate;
        Date banDate;

        try {
            TournamentDate date = dates.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    //No hace nada
                    break;
                case 1: {
                    if ( ! newDate.isEmpty() ) {
                        if ( validateDateString( newDate ) ) {
                            if ( getValueAt(rowIndex, 2) != null ) {
                                initialDate = formatTournamentDate.parse( newDate + " " + getValueAt(rowIndex, 2) + ".0" );
                                date.setInitialDate( initialDate );
                                break;
                            } else {
                                initialDate = formatTournamentDate.parse( newDate + " " + "00:00:00" + ".0" );
                                date.setInitialDate( initialDate );
                                break;
                            }                            
                        } else {
                            JOptionPane.showMessageDialog(null,
                                    "<html>El campo <strong>Fecha inicial</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>no contiene una fecha válida.</html>",
                                    "Error:Fecha inicial inválida",
                                    JOptionPane.ERROR_MESSAGE);
                            break;
                        }
                    } else {
                        initialDate = null;
                        date.setInitialDate( initialDate );
                        break;
                    }
                }
                case 2: {
                    if ( ! newDate.isEmpty() ) {
                        if ( validateTimeString( (String) newDate ) ) {
                            if ( getValueAt(rowIndex, 1) != null ) {
                                initialDate = formatTournamentDate.parse( getValueAt(rowIndex, 1) + " " + newDate + ".0" );
                                date.setInitialDate( initialDate );
                                break;
                            } else {
                                JOptionPane.showMessageDialog(null,
                                    "<html>Complete el campo <strong>Fecha inicial</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>antes de ingresar su correspondiente hora inicial.</html>",
                                    "Error:Hora inicial inválida",
                                    JOptionPane.ERROR_MESSAGE);
                                break;
                            }
                        } else {
                            JOptionPane.showMessageDialog(null,
                                    "<html>El campo <strong>Hora inicial</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>no contiene una hora válida.</html>",
                                    "Error:Hora inicial inválida",
                                    JOptionPane.ERROR_MESSAGE);
                            break;
                        }
                    } else {
                        initialDate = null;
                        date.setInitialDate( initialDate );
                        break;
                    }
                }                    
                case 3: {
                    if ( getValueAt(rowIndex, 1) != null ) {
                        if ( ! newDate.isEmpty() ) {
                            if ( validateDateString( (String) newDate ) ) {
                                if ( getValueAt(rowIndex, 4) != null ) {
                                    banDate = formatTournamentDate.parse( newDate + " " + getValueAt(rowIndex, 4) + ".0" );
                                    date.setBanDate( banDate );
                                    break;
                                } else {
                                    banDate = formatTournamentDate.parse( newDate + " " + "00:00:00" + ".0" );
                                    date.setBanDate( banDate );
                                    break;
                                }
                            } else {
                                JOptionPane.showMessageDialog(null,
                                    "<html>El campo <strong>Fecha final</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>no contiene una fecha válida.</html>",
                                    "Error:Fecha final inválida",
                                    JOptionPane.ERROR_MESSAGE);
                                break;
                            }
                        } else {
                            banDate = null;
                            date.setBanDate( banDate );
                            break;
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                            "<html>Para setear el campo <strong>Fecha Final</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>primero debe completar su respectivo campo <strong>Fecha Inicial</strong> .</html>",
                            "Error:Fecha final inválida",
                            JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                }
                case 4: {                    
                    if ( ! newDate.isEmpty() ) {
                        if ( validateTimeString( (String) newDate ) ) {
                            if ( getValueAt(rowIndex, 3) != null ) {
                                banDate = formatTournamentDate.parse( getValueAt(rowIndex, 3) + " " + newDate + ".0" );
                                date.setBanDate( banDate );
                                break;
                            } else {
                                JOptionPane.showMessageDialog(null,
                                        "<html>Complete el campo <strong>Fecha final</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>antes de ingresar su correspondiente hora final.</html>",
                                        "Error:Hora final inválida",
                                        JOptionPane.ERROR_MESSAGE);
                                break;
                            }
                        } else {
                            JOptionPane.showMessageDialog(null,
                                    "<html>El campo <strong>Hora final</strong> de la <strong>Fecha " + (rowIndex + 1) + "</strong><br>no contiene una hora válida.</html>",
                                    "Error:Hora final inválida",
                                    JOptionPane.ERROR_MESSAGE);
                            break;
                        }
                    } else {
                        banDate = null;
                        date.setBanDate( banDate );
                        break;
                    }
                }
                case 5:
                    //No hace nada                   
                    break;
            }
        } catch (Exception e) {
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        if ( ( columnIndex == 5 ) || ( columnIndex == 0 ) || ( dates.get(rowIndex).getState().equals(TournamentDate.CLOSED_DATE) ) ) {
            return false;
        } else if ( rowIndex == 0 ) {
            return true;
        } else if ( dates.get(rowIndex - 1).getState().equals(TournamentDate.OPEN_DATE) ) {
            return false;
        } else {
            return true;
        }
    }
    
    private boolean validateDateString( String date ) {
        return Pattern.matches("\\d{1,2}/\\d{1,2}/\\d\\d\\d\\d", date );
    }

    private boolean validateTimeString( String time ) {
        return Pattern.matches("\\d{1,2}:\\d{1,2}:\\d{1,2}", time );
    }
}
